import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, Modal, message as msg} from 'antd';
import {
    FORM_OPTIONS,
    TABLE,
    PAGINATION_OPTIONS,
    PAGE,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    ROWSELECTION_FIXED_COLUMN_WIDTH,
    DATE_FORMAT
} from '../constants';
import TextInput from 'Shared/components/TextInput';
import {conventSorter} from './utils';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {getPartSaleOrders, getDealersQuickly} from './api';
import styles from './style.css';
import SelectAlert from '../common/SelectAlert';
import {partOrderStatus, paymentType, partOrderPriceTerms, transportType, currency} from '../Enum';
import SearchSelect from 'Shared/components/SearchSelect';
import DealerSelectPanel from './DealerSelectPanel';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
const FormItem = Form.Item;
import moment from 'moment';
class PartSaleOrderSelectPanel extends PureComponent {
    state = {
        keys: [],
        rows: [],
        code: '',
        dealerId: '',
        dealerCode: '',
        dealerName: '',
        brandId: '',
        partOrderTypeId: '',
        customerOrderCode: '',
        submitTime: undefined,
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        isFetching: false,
        data: {},
        message: '',
        currentCondition: {},
        showDealerSelectPanel: false,
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }
    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
    // eslint-disable-next-line react/sort-comp
    onQuery = condition => {
        this.setState({isFetching: true});
        getPartSaleOrders(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const conventDate = (condition = {}) => {
            const {submitTime, ...others} = condition;
            if(!submitTime || submitTime.length === 0) return condition;
            return {
                ...others,
                beginSubmitTime: moment(submitTime[0]).toISOString(),
                endSubmitTime: moment(submitTime[1]).toISOString(),
            };
        };
        const currentCompany = this.props.initEnum.currentCompany;
        const isDealerUser = this.props.isDealerUser;
        
        const condition = {
            code: this.state.code,
            dealerId: isDealerUser ? currentCompany.id : this.state.dealerId,
            brandId: this.state.brandId,
            partOrderTypeId: this.state.partOrderTypeId,
            customerOrderCode: this.state.customerOrderCode,
            submitTime: this.state.submitTime,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(conventDate(condition));
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    onClickReset = () => {
        this.setState({
            code: '',
            name: ''
        });
    }
    onCloseTag = () => {
        this.setState({
            keys: [],
            rows: []
        });
    }
    onChangeRadio = (keys, rows) => {
        this.setState({
            keys,
            rows
        });
    }
    onSubmit = () => {
        if(!this.state.rows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'PartSaleOrderSelectPanel.validate.queryDealer',
                defaultMessage: '请选择查询总代'
            }));
        this.props.onSelect(this.state.rows[0]);
    }
    onSearchDealer = value =>
        getDealersQuickly({filter: value})
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            })
    onSelectDealer = data => {
        this.setState({
            showDealerSelectPanel: false,
            dealerId: data.id,
            dealerCode: data.code,
            dealerName: data.name,
        });
    }
    dealerLabelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `(${d.code}) ${d.name}`;
        return '';
    }
    onClickSearchDealerBtn = () => {
        this.setState({showDealerSelectPanel: true});
    }
    onCloseDealerSelectPanel = () => {
        this.setState({showDealerSelectPanel: false});
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const dealerInfo = this.state.dealerId ? {
            id: this.state.dealerId,
            code: this.state.dealerCode,
            name: this.state.dealerName,
        } : null;
        const columns = [
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.code',
                    defaultMessage: '订单编号'
                }),
                dataIndex: 'code',
                sorter: true
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.dealerCode',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'dealerCode',
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.country',
                    defaultMessage: '国家'
                }),
                dataIndex: 'country',
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.status',
                    defaultMessage: '订单状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(partOrderStatus, text)
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.brandCode',
                    defaultMessage: '品牌编号'
                }),
                dataIndex: 'brandCode',
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.customerOrderCode',
                    defaultMessage: '客户订单号'
                }),
                dataIndex: 'customerOrderCode',
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.partOrderTypeName',
                    defaultMessage: '订单类型'
                }),
                dataIndex: 'partOrderTypeName',
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.partOrderPriceTerms',
                    defaultMessage: '价格条款'
                }),
                dataIndex: 'partOrderPriceTerms',
                render: text => conventEnumValueToString(partOrderPriceTerms, text)
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.paymentType',
                    defaultMessage: '付款方式'
                }),
                dataIndex: 'paymentType',
                render: text => conventEnumValueToString(paymentType, text)
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.transportType',
                    defaultMessage: '运输方式'
                }),
                dataIndex: 'transportType',
                render: text => conventEnumValueToString(transportType, text)
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.totalQuantity',
                    defaultMessage: '订购数量'
                }),
                dataIndex: 'totalQuantity',
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.totalAmount',
                    defaultMessage: '订单总金额'
                }),
                dataIndex: 'totalAmount',
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            },
            {
                title: formatMessage({
                    id: 'PartSaleOrderSelectPanel.column.submitTime',
                    defaultMessage: '提报日期'
                }),
                dataIndex: 'submitTime',
                render: text => formatDateTime(text, DATE_FORMAT)
            }
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const onRow = record => ({
            onDoubleClick: () => {
                // 双击选中
                this.props.onSelect(record);
            }
        });
        const rowSelection = {
            type: 'radio',
            fixed: true,
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            onChange: this.onChangeRadio,
            selectedRowKeys: this.state.keys,
        };
        const selectRows = this.state.rows.length ? [{
            text: this.state.rows[0].code,
            value: this.state.rows[0].id
        }] : [];
        return (
            <Modal
                title={formatMessage({
                    id: 'PartSaleOrderSelectPanel.show.partSaleOrderQuery',
                    defaultMessage: '备件销售订单查询'
                })}
                width="70%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'PartSaleOrderSelectPanel.show.code',
                            defaultMessage: '订单编号'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="code"
                                value={this.state.code}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    {!this.props.isDealerUser &&
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.dealerCode',
                                    defaultMessage: '总代编号'
                                })}
                                {...FORM_OPTIONS.item} >
                                <SearchSelect
                                    allowClear
                                    placeholder={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.pleaseQuery',
                                        defaultMessage: '请输入查询'
                                    })}
                                    value={dealerInfo}
                                    onSelect={this.onSelectDealer}
                                    onSearch={this.onSearchDealer}
                                    keyIndex="id"
                                    labelMap={this.dealerLabelMap}
                                    onClickSearchBtn={this.onClickSearchDealerBtn} />
                            </FormItem>
                        </Col>
                    }
                    {this.props.initEnum.brands && this.props.initEnum.brands.length > 1 &&
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.brandId',
                                    defaultMessage: '品牌'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={this.state.brandId}
                                    options={this.props.initEnum.brands}
                                    onChange={this.onChange} />
                            </FormItem>
                        </Col>
                    }
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.partOrderTypeId',
                                defaultMessage: '订单类型'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="partOrderTypeId"
                                value={this.state.partOrderTypeId}
                                options={this.props.initEnum.partSaleOrderTypes}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.customerOrderCode',
                                defaultMessage: '客户订单号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="customerOrderCode"
                                value={this.state.customerOrderCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.submitTime',
                                defaultMessage: '提报日期'
                            })}
                            {...FORM_OPTIONS.item}>
                            <DateRangePicker name="submitTime" value={this.state.submitTime}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            className={styles.btnMargin}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'PartSaleOrderSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'PartSaleOrderSelectPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                    {
                        this.state.showDealerSelectPanel &&
                        <DealerSelectPanel
                            selectKey={data.dealerId}
                            onCancel={this.onCloseDealerSelectPanel}
                            onSelect={this.onSelectDealer} />
                    }
                </Row>
                <Divider className={styles.divider}/>
                <SelectAlert data={selectRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    onRow={onRow}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    {...TABLE}
                    locale={{
                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }} />
            </Modal >
            
        );
    }
}
PartSaleOrderSelectPanel.propTypes = {
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    onCancel: PropTypes.func,
    onSelect: PropTypes.func,
};
import {connect} from 'react-redux';
import {createSelector} from 'reselect';
const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const currentCompany = initData.currentCompany;
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const partSaleOrderTypes = initData.partSaleOrderTypes ? initData.partSaleOrderTypes.map(item => ({
            text: `${item.typeName}`,
            value: item.id
        })) : [];
        return {
            currentCompany,
            brands,
            partSaleOrderTypes
        };
    }
);

const mapStateToProps = state => ({
    initEnum: getInitData(state),
});
import {injectIntl} from './intl';
export default connect(mapStateToProps, null)(injectIntl(PartSaleOrderSelectPanel));
